import base64, json, sys, time, os, traceback, random
from io import BytesIO
from PIL import Image, ImageDraw
from flask import Flask, request
from flask_cors import CORS

def generate_slide_image(origin:str)-> dict:
    """生成滑动图片及背景等信息

    Args:
        origin (str): 原图路径

    Returns:
        dict: 返回滑动图片及背景等信息
    """
    img = Image.open(origin) # 读取图片
    # 裁剪一个50*50的图像，高度取图像中间位置
    #   x1,y1
    #x,y
    img_width = img.width
    img_height = img.height
    half_height = int(img_height / 2)
    x = random.randint(50, img_width-50)
    x1 = x+50
    # 裁剪
    img_cut = img.crop((x,half_height,x1,half_height+50))
    img_cut.save('./images/generate/cut.png', 'png')#测试图片生成
    buf = BytesIO()
    img_cut.save(buf, 'png')
    buf.seek(0)
    img_bytes = buf.read()
    base64_encoded_result_bytes = base64.b64encode(img_bytes)
    base64_encoded_result_str = base64_encoded_result_bytes.decode('ascii')
    # 偏移量为x
    print(x)
    # 偏移率保留2位小数
    slide_rate = x / img_width
    slide_rate_f = '%.2f' %slide_rate
    print(slide_rate_f)
    #透明
    transparent_area = (x,half_height,x1,half_height+50) 
    mask=Image.new('L', img.size, color=255) 
    draw=ImageDraw.Draw(mask) 
    draw.rectangle(transparent_area, fill=0) 
    img.putalpha(mask) 
    img.save('./images/generate/transparent.png')
    bk_buf = BytesIO()
    img.save(bk_buf, 'png')
    bk_buf.seek(0)
    bk_img_bytes = bk_buf.read()
    bk_base64_encoded_result_bytes = base64.b64encode(bk_img_bytes)
    bk_base64_encoded_result_str = bk_base64_encoded_result_bytes.decode('ascii')
    return {
        'bk_img_base64': bk_base64_encoded_result_str,#底图
        'cut_img_base64': base64_encoded_result_str,#裁剪50*50图
        'uuid':unique_id(),#唯一id
        'slide_rate': slide_rate_f,#偏移率
        'slide_width': x#偏移量
    }
    
def unique_id(prefix='')->str:
    """ uuid,唯一id 
        return string id
    """
    return prefix + hex(int(time.time()))[2:10] + hex(int(time.time() * 1000000) % 0x100000)[2:7]


#generate_slide_image("./images/original/bg16.png")

###########################################

# Use Demo

###########################################
app = Flask(__name__,static_folder=os.getcwd()+'/images')
g = dict()
@app.route('/api/slide/image/create', methods=['GET'])
def get_slide_image():
    """获取拖拉图片及uuid

    Returns:
        _type_: 返回拖拉图片及uuid
    """
    data = generate_slide_image("./images/original/bg16.png")
    g[data['uuid']] = {
        'slide_rate': data['slide_rate'],#偏移率
        'slide_width': data['slide_width']#偏移量
    }
    del data['slide_rate']
    del data['slide_width']
    return data

@app.route('/api/slide/image/verify/width', methods=['POST'])
def verify_width():
    """认证偏移距离

    Returns:
        _type_: 返回认证结果
    """
    requests = request.get_json()
    uuid = requests['uuid']
    slide_width = requests['slide_width']
    try:
        data = g[uuid]
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        error_trace = traceback.format_exception(exc_type, exc_value, exc_traceback)
        return {"status":False, "error": json.dumps(error_trace)}
    status = False
    if (slide_width > (data['slide_width']-5)) and (slide_width < (data['slide_width']+5)):
        status = True
    del g[uuid]
    return {"status":status}

@app.route('/api/slide/image/verify/rate', methods=['POST'])
def verify_rate():
    """认证偏移率

    Returns:
        _type_: 返回认证结果
    """
    requests = request.get_json()
    uuid = requests['uuid']
    slide_rate = requests['slide_rate']
    data = g[uuid]
    status = False
    if slide_rate == data['slide_rate']:
        status = True
    del g[uuid]
    return status
    


if __name__ == '__main__':
    CORS(app, supports_credentials=True)
    app.debug = False
    app.run(host='0.0.0.0', port=500)